package top.wangkylin.util;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import top.wangkylin.domain.PdfParam;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.List;

/**
 * Pdf的工具类
 *
 * @author WQ
 */
public class PdfUtil {

    public static File makePdf(List<PdfParam> pdfParams, String fileName, String pdfName) {
        OutputStream os = null;
        File file = null;
        String realPath = PdfUtil.class.getClassLoader().getResource("").getPath();
        try {
            PdfReader reader = new PdfReader(realPath + File.separator + pdfName);
            file = new File(realPath + File.separator + fileName);
            os = Files.newOutputStream(file.toPath());
            PdfStamper ps;
            ps = new PdfStamper(reader, os);

            /* 使用中文字体 */
//			BaseFont bf = BaseFont.createFont(realPath + templatePath
//					+ "/simsun.ttc,1", BaseFont.IDENTITY_H,
//					BaseFont.EMBEDDED);
//			ArrayList<BaseFont> fontList = new ArrayList<>();
//			fontList.add(bf);

            AcroFields form = ps.getAcroFields();
//			s.setSubstitutionFonts(fontList);

            for (PdfParam pdfParam : pdfParams) {
                if (pdfParam.getIsImg()) {
                    String imgFieldName = pdfParam.getFieldName();
                    String imagePath = pdfParam.getFieldValue();
                    
                    // 检查字段是否存在于PDF模板中
                    if (form.getFieldPositions(imgFieldName) == null || form.getFieldPositions(imgFieldName).isEmpty()) {
                        System.out.println("警告：PDF模板中不存在字段: " + imgFieldName);
                        continue;
                    }
                    
                    int pageNo = form.getFieldPositions(imgFieldName).get(0).page;
                    Rectangle signRect = form.getFieldPositions(imgFieldName).get(0).position;
                    float x = signRect.getLeft();
                    float y = signRect.getBottom();
                    // 读图片
                    Image image = Image.getInstance(imagePath);
                    // 获取操作的页面
                    PdfContentByte under = ps.getOverContent(pageNo);
                    // 根据域的大小缩放图片，拉伸占满空间
                    image.scaleAbsolute(signRect.getWidth(), signRect.getHeight());
                    // 添加图片
                    image.setAbsolutePosition(x, y);
                    under.addImage(image);
                } else {
                    // 检查文本字段是否存在
                    if (form.getField(pdfParam.getFieldName()) != null) {
                        form.setField(pdfParam.getFieldName(), pdfParam.getFieldValue());
                    } else {
                        System.out.println("警告：PDF模板中不存在字段: " + pdfParam.getFieldName());
                    }
                }
            }

            ps.setFormFlattening(true);
            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}
